// 云函数入口文件
const cloud = require('wx-server-sdk')
const cheerio = require('cheerio');
const axios = require('axios');


cloud.init()
async function parseAvatar(account) {
  //解析地址
  //https://home.cnblogs.com/u/masterchd
  return new Promise(function(resolve,reject){
     axios.get('https://home.cnblogs.com/u/' + account)
    .then(function (response) {
      // console.log(response);
      console.log(response)
      let htmldata = response.data;
      $ = cheerio.load(htmldata)
      let avatar = $('.user_avatar img').attr('src')
      console.log(avatar)
      //console.log(htmldata)
      resolve('https:'+avatar)
    })
    .catch(function (error) {
     reject(error)
    });
  })
  
}

function parseBilbili(htmldata) {
  //解析对应函数
  $ = cheerio.load(htmldata)
  // let avatar = $('#lnkBlogLogo').html();
  let reshtml = $('#cnblogs_post_body').html();
  //console.log(reshtml);
  //console.log(avatar)
  let title = $('#cb_post_title_url span').html()
  //let desc = $('.postDesc span').children('#post-date');
  let time = $('.postDesc span#post-date').text();
  console.log(time)
  // console.log(desc)
  let author = $('.postDesc a:first').text();
  console.log(author)
  //console.log(title)
  return {
    reshtml,
    title,
    time,
    author
  }
}
// 云函数入口函数
/**
 * @可以修改为Promise.All 加快速度
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  let url = event.url;
  let theme = event.theme || 'bilibili';
  console.log('进入函数')
  var patharr = url.split('/')
  console.log(patharr)
  let account = patharr[3];
  let avatar = await parseAvatar(account);
  console.log('avatar is: '+avatar)
  return new Promise(function (resolve, reject) {
    axios.get(url)
      .then(function (response) {
        // console.log(response);
        console.log(theme)
        let htmldata = response.data;
        //console.log(htmldata)
        let ans = null;
        if (theme == 'bilibili') {
          let ans =  parseBilbili(htmldata, account);
          resolve({
            title:ans.title,
            htmldata:ans.reshtml,
            articledata:{
              avatar,
              author:ans.author,
              time:ans.time
            }
          })
        }else{
          resolve('no')
        }
        
      })
      .catch(function (error) {
        reject(error)
      });
  })
}